package com.zhouzi.zhaoyang.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.FrameLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.orhanobut.logger.Logger
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.adapter.rvadapter.TransactionQueryAdapter
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.GetCloseAccountPrint
import com.zhouzi.zhaoyang.bean.GetOrderListBean2
import com.zhouzi.zhaoyang.bean.GetOrderListPrintBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.mvp.p.TransactionQueryActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.ITransationQueryActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import com.zhouzi.zhaoyang.util.SPUtils
import com.zhouzi.zhaoyang.util.print.PrinterUtil
import kotlinx.android.synthetic.main.transaction_query_activity.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class TransactionQueryActivity : BaseActivity(), ITransationQueryActivityView,
    AdapterView.OnItemSelectedListener {


    var enter = 160
    var goodsNo = ""
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {

        if ((event?.keyCode == KeyEvent.KEYCODE_ENTER || event?.keyCode == enter)){
            goodsNo = etSearch.text.toString().trim()
            Logger.e(goodsNo)
            // 对接接口
            var map = mutableMapOf<String, Any>(
                Pair("deviceNo", deviceNo),
                Pair("outTradeNo", goodsNo)
            )
            p.getOrderList(pageNum, pageSize, map)
            return  false
        }

        return super.dispatchKeyEvent(event)
    }



    override fun errorToken() {
        exitToLogin()
    }
    override fun onNothingSelected(parent: AdapterView<*>?) {
    }

    var spinnerPosition = 1
    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        adapter?.data?.clear()
        adapter?.notifyDataSetChanged()
        spinnerPosition = position + 1
    }


    override fun allPrintSuccess(data: GetOrderListPrintBean?) {
        printData(data!!)
    }

    override fun allPrintFailed(msg: String?) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }


    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {

        orderDetail.let {

            App.instance().printOrderWithRV(orderDetail!!)
        }

    }








    override fun getOrderFailed(msg: String?) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }


    override fun getCloseAccountPrintSuccess(data: GetCloseAccountPrint?) {
        data.let {

            val util = PrinterUtil(this)

            var line = ArrayList<String>()

            line.add("结算打印")
            line.add("门店名称："+data?.storeName)
            line.add("结算店员："+data?.storeUserName)


            var cbPrintSettings1: Int = SPUtils.getInstance().getValue("cbPrintSettings0", 1) as Int
            var cbPrintSettings2: Int = SPUtils.getInstance().getValue("cbPrintSettings1", 1) as Int
            var cbPrintSettings3: Int = SPUtils.getInstance().getValue("cbPrintSettings2", 1) as Int
            var cbPrintSettings4: Int = SPUtils.getInstance().getValue("cbPrintSettings3", 1) as Int
            var cbPrintSettings5: Int = SPUtils.getInstance().getValue("cbPrintSettings4", 1) as Int
            var cbPrintSettings6: Int = SPUtils.getInstance().getValue("cbPrintSettings5", 1) as Int
            var cbPrintSettings7: Int = SPUtils.getInstance().getValue("cbPrintSettings6", 1) as Int
            var cbPrintSettings8: Int = SPUtils.getInstance().getValue("cbPrintSettings7", 1) as Int
            var cbPrintSettings9: Int = SPUtils.getInstance().getValue("cbPrintSettings8", 1) as Int

           if (cbPrintSettings1 == 2){
               line.add("交易单数："+data?.sumCount)
               line.add("交易金额："+data?.sumFee)
           }
            if (cbPrintSettings2 == 2){
                if(!TextUtils.isEmpty(data?.settlementFee) && !"null".equals(data?.settlementFee)){
                    line.add("实收金额：" + data?.settlementFee)
                }else{
                    line.add("实收金额：0" )

                }

            }

         if (cbPrintSettings4 == 2){
             line.add("退款单数：" + data?.refundCount)
             line.add("退款金额：" + data?.refundFee)
         }
           if (cbPrintSettings3 == 2){
               if(!TextUtils.isEmpty(data?.couponTotalFee) && !"null".equals(data?.couponTotalFee)){
                   line.add("优惠金额：" + data?.couponTotalFee)

               }else{
                   line.add("优惠金额：0" )

               }
           }
          if (cbPrintSettings6 == 2){
              if(!TextUtils.isEmpty(data?.depositCount.toString()) && !"null".equals(data?.depositCount)){
                  line.add("押金单数：" + data?.depositCount)


              }else{
                  line.add("押金单数：0" )

              }
              if(!TextUtils.isEmpty(data?.depositTotalFee) && !"null".equals(data?.depositTotalFee)){
                  line.add("押金金额：" + data?.depositTotalFee)


              }else{
                  line.add("押金金额：0" )

              }
          }
            if (cbPrintSettings7 == 2){
                line.add("微信单数："+data?.wxCount)
                line.add("微信金额："+data?.wxFee)
            }
            if (cbPrintSettings8 == 2){
                line.add("支付宝单数："+data?.aliCount)
                line.add("支付宝金额："+data?.aliFee)
            }
          if (cbPrintSettings5 == 2){
              line.add("会员单数："+data?.memberCount)
              line.add("会员金额："+data?.memberFee)
          }

        if (cbPrintSettings9 == 2){
            line.add("通用通单数："+data?.tytCount)
            line.add("通用通金额："+data?.tytFee)
        }

            if (!TextUtils.isEmpty(data?.beginTime) && !"null".equals(data?.beginTime)){
                line.add("开始时间："+data?.beginTime)
            }else{
                line.add("开始时间：")
            }
            line.add("结束时间："+data?.endTime+"\n\n\n\n\n")



            util.createData(line)


        }
    }

    override fun getCloseAccountPrintFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }


    private val p = TransactionQueryActivityPresenter()

    init {
        p.attachView(this)
    }


    override fun onDestroy() {
        super.onDestroy()
        p.detachView()
    }


    override fun getOrderListSuccess(data: GetOrderListBean2?) {

        smartRefresh.finishLoadMore(true)
        smartRefresh.finishRefresh(true)
        data.let {
            if (data!!.records.size == 0) {
                Toast.makeText(this, "暂无更多数据", Toast.LENGTH_SHORT).show()
                if (status == 1){
                    smartRefresh.visibility = VISIBLE
                }else if (status == 2){
                    smartRefresh.visibility = GONE
                }else{
                    smartRefresh.visibility = GONE

                }
            } else {
                smartRefresh.visibility = VISIBLE
                setData(data)
            }
        }
    }

    var getOrderListBean2 :GetOrderListBean2 ?= null
   private var adapter :TransactionQueryAdapter ?= null
    private fun setData(data: GetOrderListBean2?) {

        rv.layoutManager = LinearLayoutManager(this)

        when(status){
        1 -> selectTimeData(data)
        2 -> wxScanData(data)
        3 ->getOrderNo(data)
    }

    }

    private fun getOrderNo(data: GetOrderListBean2?) {

        adapter = TransactionQueryAdapter(R.layout.transaction_query_rv, data!!.records)
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            p.getOrder(data.records[position].outTradeNo)
        }
        rv.adapter = adapter

    }

    private fun wxScanData(data: GetOrderListBean2?) {

        adapter = TransactionQueryAdapter(R.layout.transaction_query_rv, data!!.records)
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            p.getOrder(data.records[position].outTradeNo)
        }
        rv.adapter = adapter


    }

    private fun selectTimeData(data: GetOrderListBean2?) {

        if(loadMore && getOrderListBean2 != null   ){
            data?.records?.addAll(getOrderListBean2!!.records)
        }
        adapter = TransactionQueryAdapter(R.layout.transaction_query_rv, data!!.records)
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            p.getOrder(data.records[position].outTradeNo)
        }
        adapter?.setOnItemClickListener { adapter, view, position ->

            val detail = Intent(this,TransactionQueryDetailActivity :: class.java)
            detail.putExtra("data",data.records[position])
            startActivity(detail)

        }
        rv.adapter = adapter
        getOrderListBean2 = data
    }


    override fun getOrderListFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
        smartRefresh.finishLoadMore(false)
        smartRefresh.finishRefresh(false)
    }

    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()

    }

    override fun getLayoutId(): Int {
        return R.layout.transaction_query_activity
    }

    var loadMore = true
    override fun initView() {

        initList()

        spinnerQuery.onItemSelectedListener = this

        viewClick()

        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (isSuccessInfo(p0)) {


                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })



        smartRefresh.setOnRefreshListener {
            loadMore = false
            pageNum = 1
            getOrderList(pageNum,tvShowSelect.text.toString())
        }
        smartRefresh.setOnLoadMoreListener {
            loadMore = true
            pageNum++
            getOrderList(pageNum,tvShowSelect.text.toString())
        }

    }


    override fun onStart() {
        super.onStart()
        smartRefresh.autoRefresh()
    }

    private fun initList() {
        status = 1
        pageNum = 1
        adapter?.data?.clear()
        adapter?.notifyDataSetChanged()
        val time = getTime(Date())
        startTime = time
        tvShowSelect.text =startTime
        getOrderListWithTime(1,time)
    }

    /*判断回调是否异常*/
    private fun isSuccessInfo(info: Map<*, *>?): Boolean {


        if (info == null) {
            RuntimeException("调用返回为空").printStackTrace()
            return false
        }
        val code = info["return_code"] as String
        val msg = info["return_msg"] as String
        Log.d("response parameter", "response | getWxpayfaceRawdata $code | $msg")
        if (code == null || info.get("rawdata").toString() == null || !code.equals("SUCCESS")) {
            RuntimeException("调用返回非成功信息,return_msg:" + msg + "   ").printStackTrace()
            return false
        }
        return true
    }



    var pageNum= 1
    var pageSize = 20
    var deviceNo = Build.SERIAL
    var startTime = ""
    var status = -1
    private var pvTime: TimePickerView? = null
    private fun viewClick() {


        ivDelShowTime.setOnClickListener {
            tvShowSelect.setText("")
        }


        tvSelectDate.setOnClickListener {
            etSearch.setText("")
            status = 1
            pageNum = 1
            adapter?.data?.clear()
            adapter?.notifyDataSetChanged()
            initTimePicker(this)

        }




//        search.setOnCloseListener(SearchView.OnCloseListener {
//            spinnerQuery.visibility = VISIBLE
//            llPrint.visibility = VISIBLE
//            return@OnCloseListener false
//        })
//
//
//        search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
//
//            override fun onQueryTextSubmit(query: String?): Boolean {
//                return true
//            }
//
//            override fun onQueryTextChange(newText: String?): Boolean {
//                spinnerQuery.visibility = GONE
//                llPrint.visibility = GONE
//                return false
//            }
//
//        })

        btnQuery.setOnClickListener {


            if (!TextUtils.isEmpty(etSearch.text.toString())) {
                // 对接接口
                var map = mutableMapOf<String, Any>(
                    Pair("deviceNo", deviceNo),
                    Pair("outTradeNo", etSearch.text.toString())
                )
                status = 3
                p.getOrderList(pageNum, pageSize, map)
            } else {
                Toast.makeText(this, "请输入搜索条件", Toast.LENGTH_SHORT).show()
            }

        }

        tvWXScan.setOnClickListener {

            etSearch.setText("")


            val scanIntent = Intent(this, VoiceService::class.java)
            scanIntent.putExtra("voiceStr", "请对准上方摄像头扫码")
            startService(scanIntent)

            WxPayFace.getInstance().startCodeScanner(object : IWxPayfaceCallback() {


                override fun response(info: MutableMap<Any?, Any?>?) {

                    Handler(Looper.getMainLooper()).post {


                        Log.e("startCodeScanner", info.toString())

                        if (info != null) {
                            var return_code = info.get("return_code")
                            var return_msg = info.get("return_msg")
                            var code_msg = info.get("code_msg")
                            var resultString =
                                "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg

                            etSearch.setText("")
                            etSearch.setText(code_msg.toString())

                            if (!TextUtils.isEmpty(etSearch.text.toString())) {
                                // 对接接口
                                var map = mutableMapOf<String, Any>(
                                    Pair("deviceNo", deviceNo),
                                    Pair("outTradeNo", etSearch.text.toString())
                                )
                                p.getOrderList(pageNum, pageSize, map)
                            } else {

                                val scanIntent2 = Intent(mContext, VoiceService::class.java)
                                scanIntent2.putExtra("voiceStr", "请重新输入搜索条件")
                                startService(scanIntent2)
                            }

                        }

                    }


                }
            })


        }

        tvApBtn.setOnClickListener {
            finish()
        }


        tvAllPrint.setOnClickListener {

            if (!TextUtils.isEmpty(tvShowSelect.text.toString())){
                val map = mutableMapOf(
                        Pair("deviceNo",deviceNo),
                        Pair("beginTime", tvShowSelect.text.toString())
                )
                p.allPrint(map)
            }else{

                Toast.makeText(this,"请选择日期",Toast.LENGTH_SHORT)

            }


//            allPrint(spinnerPosition)

        }


        tvAccountPrint.setOnClickListener {
            if (!TextUtils.isEmpty(tvShowSelect.text.toString())){
                getCloseAccountPrint(tvShowSelect.text.toString())
            }else{
                Toast.makeText(this,"请选择结算日期",Toast.LENGTH_SHORT)
            }
        }

    }

    fun initTimePicker(context: Context) {

        pvTime = TimePickerBuilder(context,
            OnTimeSelectListener { date, v ->

                val time = getTime(date)
                startTime = time
                tvShowSelect.text =startTime
                getOrderListWithTime(1,time)
            })
            .setTimeSelectChangeListener { Log.i("pvTime", "onTimeSelectChanged") }
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
            .addOnCancelClickListener { Log.i("pvTime", "onCancelClickListener") }
            .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
            .setLineSpacingMultiplier(2.0f)
            .isAlphaGradient(true)
            .build()

        val mDialog = pvTime!!.dialog
        if (mDialog != null) {

            val params = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                Gravity.BOTTOM
            )

            params.leftMargin = 0
            params.rightMargin = 0
            pvTime!!.dialogContainerLayout.layoutParams = params

            val dialogWindow = mDialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f)
            }
        }

        pvTime!!.show()

    }


    private fun getTime(date: Date): String {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.time)
        val format = SimpleDateFormat("yyyy-MM-dd")
        return format.format(date)
    }

    private fun getCloseAccountPrint( beginTime: String) {
        var map = mutableMapOf<String, Any>(
            Pair("deviceNo", deviceNo)
        )
        map.put("beginTime", beginTime)
        p.getCloseAccountPrint(map)
    }

    private fun getOrderList(pageNum :Int, outTradeNo: String) {

        var map = mutableMapOf<String, Any>(
            Pair("deviceNo", deviceNo)
        )
        map.put("outTradeNo",outTradeNo)
        p.getOrderList(pageNum, pageSize, map)
    }

    private fun getOrderListWithTime(pageNum :Int, beginTime: String) {

        var map = mutableMapOf<String, Any>(
            Pair("deviceNo", deviceNo)
        )
        map.put("beginTime", beginTime)
        p.getOrderList(pageNum, pageSize, map)
    }



//    fun allPrint(deviceNo: String, beginTime: String, token: String, context: Context){
//
//        OkHttpUtils
//            .post()
//            .url(HttpConfig.BASE_URL + "/api/face/getOrderListPrint")
//            .addParams("Access-Token", token)
//            .addParams("deviceNo", deviceNo)
//            .addParams("beginTime", beginTime)
//            .build()
//            .execute(object : StringCallback() {
//                override fun onError(call: Call, e: Exception, id: Int) {
//                    Log.e("onError", e.message)
//                }
//
//                override fun onResponse(response: String, id: Int) {
//                    Log.e("onResponse", response)
//                    val gson = Gson()
//                    val myAllPrintBean = gson.fromJson(response, MyAllPrintBean::class.java)
//                    if (myAllPrintBean.code == 200) {
//                        print(myAllPrintBean)
//                    } else {
//                        Toast.makeText(context, "服务器连接超时，请稍后再试", Toast.LENGTH_LONG).show()
//                    }
//                }
//            })
//
//    }

    private fun printData(data: GetOrderListPrintBean) {

        if (data.list.size > 0) {
            val util = PrinterUtil(this)
            var line = ArrayList<String>()
            line.add("明细打印\n")
            line.add("门店名称：" + data.list[0].storeName + "\n")

            for (i in 0 until data.list.size) {
                val records = data.list[i]
//
//                if (i == data!!.result.size - 1) {
//                    if (records[i].orderStatus == 1) {
//                        line.add(
//                            records[i].outTradeNo + " " + Calculator.fen2Yuan(records[i].memberTotalFee.toLong()).toString() + "元 " + "付款\n\n\n\n" +
//                                    "\n" +
//                                    "\n"
//                        )
//                    } else if (records[i].orderStatus == 3) {
//                        line.add(
//                            records[i].outTradeNo + " " + Calculator.fen2Yuan(records[i].memberTotalFee.toLong()).toString() + "元 " + "退款\n\n\n\n" +
//                                    "\n" +
//                                    "\n"
//                        )
//                    }
//                } else {
                    if (records.orderStatus == 1) {
                        line.add(records.outTradeNo + " " + Calculator.fen2Yuan(records.memberTotalFee.toLong()).toString() + "元 " + "已付款")
                    } else if (records.orderStatus == 3) {
                        line.add(records.outTradeNo + " " + Calculator.fen2Yuan(records.memberTotalFee.toLong()).toString() + "元 " + "退款")
                    }
//                }


            }

            line.add("开始时间：" + data.beginTime )
            line.add("结束时间：" + data.endTime + "\n\n\n\n\n")

            util.createData(line)
        }

    }


}
